package user

import (
	"bytes"
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/redis_lib"
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"time"
)

// 订单查询
func Orderfhxcx(ctx *gin.Context) {

	out_trade_no := "17310329366744414313104"
	var user models.User
	data_source.Db.Where("id = 21538").First(&user)
	data := UploadShippingInfo(out_trade_no, user)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type T4 struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

// 发货
func UploadShippingInfo(out_trade_no string, user models.User) (data T4) {
	token := Accesstokensj()
	order_key := OrderKey{
		OrderNumberType: 1,
		Mchid:           mchID,
		OutTradeNo:      out_trade_no,
	}
	shipping_list := ShippingList{
		ItemDesc: "潮玩",
	}
	var shipping_lists []ShippingList
	shipping_lists = append(shipping_lists, shipping_list)
	payer := Payer{
		Openid: user.RoutineOpenid,
	}
	request := T3{
		OrderKey:      order_key,
		DeliveryMode:  1,
		LogisticsType: 3,
		ShippingList:  shipping_lists,
		UploadTime:    time.Now(),
		Payer:         payer,
	}
	//marshal2, _ := json.Marshal(request)
	body, _ := json.Marshal(request)
	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token="+token, bytes.NewBuffer(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("access-token", token)
	resp, err := client.Do(req)
	defer resp.Body.Close()
	body1, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body1))

	r := T4{}
	err = json.Unmarshal(body1, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type OrderKey struct {
	OrderNumberType int    `json:"order_number_type"`
	Mchid           string `json:"mchid"`
	OutTradeNo      string `json:"out_trade_no"`
}
type ShippingList struct {
	ItemDesc string `json:"item_desc"`
}
type Payer struct {
	Openid string `json:"openid"`
}
type T3 struct {
	OrderKey      OrderKey       `json:"order_key"`
	DeliveryMode  int            `json:"delivery_mode"`
	LogisticsType int            `json:"logistics_type"`
	ShippingList  []ShippingList `json:"shipping_list"`
	UploadTime    time.Time      `json:"upload_time"`
	Payer         Payer          `json:"payer"`
}

// 订单查询
func Orderlistxcx(ctx *gin.Context) {
	data := GetOrderList()

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return
}

type T struct {
	PayTimeRange PayTimeRange `json:"pay_time_range"`
	PageSize     int          `json:"page_size"`
}
type PayTimeRange struct {
	BeginTime int `json:"begin_time"`
	EndTime   int `json:"end_time"`
}
type T2 struct {
	Errcode   int    `json:"errcode"`
	Errmsg    string `json:"errmsg"`
	OrderList []struct {
		TransactionId   string `json:"transaction_id"`
		MerchantTradeNo string `json:"merchant_trade_no"`
		MerchantId      string `json:"merchant_id"`
		SubMerchantId   string `json:"sub_merchant_id"`
		Description     string `json:"description"`
		PaidAmount      int    `json:"paid_amount"`
		Openid          string `json:"openid"`
		TradeCreateTime int    `json:"trade_create_time"`
		PayTime         int    `json:"pay_time"`
		OrderState      int    `json:"order_state"`
		InComplaint     bool   `json:"in_complaint"`
		Shipping        struct {
		} `json:"shipping"`
	} `json:"order_list"`
	LastIndex string `json:"last_index"`
	HasMore   bool   `json:"has_more"`
}

func GetOrderList() (data T2) {
	token := Accesstokensj()
	fmt.Println(token)

	pay_time_range := PayTimeRange{
		BeginTime: 1727733937,
		EndTime:   1731103537,
	}
	request := T{
		PageSize:     10,
		PayTimeRange: pay_time_range,
	}
	//marshal2, _ := json.Marshal(request)
	body, _ := json.Marshal(request)
	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://api.weixin.qq.com/wxa/sec/order/get_order_list?access_token="+token, bytes.NewBuffer(body))

	if err != nil {
		panic(err)
	}
	req.Header.Set("access-token", token)
	resp, err := client.Do(req)
	defer resp.Body.Close()
	body1, err := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body1))

	//
	r := T2{}
	err = json.Unmarshal(body1, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type ResponseAccess struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
}

func Accesstokensj() (data string) {
	ctx := context.Background()
	weixintoken, _ := redis_lib.Client.Get(ctx, "weixinAccesstokendchaowanxcx").Result()
	if weixintoken == "" || len(weixintoken) == 0 {
		resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret)

		if err != nil {
			fmt.Println(err)
			return
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		r := ResponseAccess{}
		//fmt.Println("token----------", string(body))

		//把请求到的结构反序列化到专门接受返回值的对象上面
		err = json.Unmarshal(body, &r)
		if err != nil {
			fmt.Println(err)
		}
		weixintoken = r.AccessToken
		redis_lib.Client.Set(ctx, "weixinAccesstokendchaowanxcx", weixintoken, 7000*time.Second)
	}
	return weixintoken

}
